package com.example.easycharge.controller;

import com.alibaba.fastjson.JSONObject;
import com.example.easycharge.entity.MessageItem;
import com.example.easycharge.error.MessageNotFoundError;
import com.example.easycharge.error.UserNotFoundError;
import com.example.easycharge.repository.CustomerRepository;
import com.example.easycharge.repository.MessageItemRepository;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Tag(name = "消息接口组")
@RestController
@RequestMapping("messageItem")
public class MessageItemController {
    @Autowired
    private MessageItemRepository messageItemRepository;
    @Autowired
    private CustomerRepository customerRepository;

    @Operation(description = "发送一个新消息，严格来说是管理员接口")
    @PostMapping("admin")
    public JSONObject sendMessage(@RequestBody MessageItem messageItem) throws UserNotFoundError {
        JSONObject jsonObject = new JSONObject();
        // 检验用户是否存在
        int userExist = customerRepository.countCustomerByUserId(messageItem.getCustomerId());
        if (userExist == 0) {
            throw new UserNotFoundError("用户" + messageItem.getCustomerId() + "不存在");
        }
        messageItem.setSendDate(new Date());
        messageItem.setHasRead(false);
        messageItemRepository.save(messageItem);
        jsonObject.put("message", "消息发送成功");
        return jsonObject;
    }

    @Operation(description = "将某个消息设置为已读，和前端配合的话就是点开这个消息后就发一个“读请求”表示已经读取了这个消息")
    @PutMapping("readMsg/{messageId}")
    public JSONObject readMessage(@PathVariable("messageId") long messageId) throws MessageNotFoundError {
        JSONObject jsonObject = new JSONObject();
        int messageExist = messageItemRepository.countAllByMessageItemId(messageId);
        // 没找到这个消息
        if (messageExist == 0) {
            throw new MessageNotFoundError();
        }
        messageItemRepository.readMessageByMessageId(messageId);
        jsonObject.put("message", "消息读取成功");
        return jsonObject;
    }

    @Operation(description = "读取所有的未读消息，类似清除所有未读消息吧")
    @PutMapping("readAll")
    public JSONObject readAllMessage(HttpServletRequest httpServletRequest) throws UserNotFoundError {
        long customerId = (long) httpServletRequest.getAttribute("customerId");
        JSONObject jsonObject = new JSONObject();
        int customerExist = customerRepository.countCustomerByUserId(customerId);
        if (customerExist == 0) {
            throw new UserNotFoundError();
        }
        messageItemRepository.readAllByCustomerId(customerId);
        jsonObject.put("message", "所有消息已读");
        return jsonObject;
    }

    @Operation(description = "分页拉取所有的未读消息，排序依据按照发送时间排序")
    @GetMapping("unread/{page}/{pageNum}")
    public Page<MessageItem> getUnreadMessage(HttpServletRequest httpServletRequest,
                                              @PathVariable("page") int page,
                                              @PathVariable("pageNum") int pageNum) {
        long customerId = (long) httpServletRequest.getAttribute("customerId");
        Pageable pageable = PageRequest.of(page - 1, pageNum, Sort.Direction.DESC, "sendDate");
        return messageItemRepository.findAllByCustomerIdAndHasRead(pageable, customerId, false);
    }

    @Operation(description = "拉取所有的消息，包括已读和未读的")
    @GetMapping("/{page}/{pageNum}")
    public Page<MessageItem> getAllMessage(HttpServletRequest httpServletRequest,
                                           @PathVariable("page") int page,
                                           @PathVariable("pageNum") int pageNum) {
        long customerId = (long) httpServletRequest.getAttribute("customerId");
        Pageable pageable = PageRequest.of(page - 1, pageNum, Sort.Direction.DESC, "sendDate");
        Page<MessageItem> totalMessagePage = messageItemRepository.findAllByCustomerId(pageable, customerId);
        return totalMessagePage;
    }

    @Operation(description = "删除某个消息，姑且设定为用户也可使用")
    @DeleteMapping("{messageId}")
    public JSONObject deleteMessage(@PathVariable("messageId") long messageId) {
        JSONObject jsonObject = new JSONObject();
        messageItemRepository.deleteMessageItemByMessageItemId(messageId);
        jsonObject.put("message", "消息删除成功");
        return jsonObject;
    }

}
